import 'dart:convert';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';

import 'package:boss/ui/page/member/page/gradeAddandEdit.dart';
import 'package:boss/ui/page/member/utils/method.dart';
import 'package:boss/ui/widget/alert/textAlert.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:router/annotation.dart';

@RouterConfig(GradeDiscount.pageName)
class GradeDiscount extends StatefulWidget {
  static const pageName = '/gradeDiscountPage';

  @Autowired()
  final bool needBack;

  GradeDiscount({
    this.needBack = false,
  });

  @override
  MyGradeDiscount createState() => MyGradeDiscount('等级优惠');
}

class MyGradeDiscount extends BaseState<GradeDiscount> {
  bool _itemSort = false;

  var cardList = [];

  //排序id集合
  List sortIdArr = [];

  MyGradeDiscount(String pageName) : super(pageName);

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration(milliseconds: 0)).then((e) {
      queryStoreMemberRankFun();
    });
  }

  //获取等级优惠list
  queryStoreMemberRankFun() async {
    try {
      Future.delayed(Duration(milliseconds: 0)).then((e) {
        showLoadingToast();
      });

      var res = await api.queryStoreMemberRank();

      if (res.successful()) {
        cardList = res.data;

        setState(() {});
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //排序
  sortModular(List idList) async {
    try {
      showLoadingToast();

      var res = await api.sortStoreMemberRank({'idList': idList});

      if (res.successful()) {
        toast("排序成功");
        queryStoreMemberRankFun();
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      Future.delayed(Duration(milliseconds: 0), () async {
        hideLoadingToast();
      });
    }
  }

  //文本表头
  textHeader() {
    return widget.needBack != true
        ? Container(
            color: Colors.white,
            padding: EdgeInsets.only(
              left: 28.w,
              right: 28.w,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 20.w,
                ),
                Row(
                  children: <Widget>[
                    Text(
                      "·",
                      style: TextStyleConstant().shallow_gray_22,
                    ),
                    Expanded(
                      child: RichText(
                        text: TextSpan(children: <TextSpan>[
                          TextSpan(
                            text: '请根据成长等级顺序添加会员等级，如需要插入等级则使用"',
                            style: TextStyleConstant().shallow_gray_22,
                          ),
                          TextSpan(
                            text: '排序等级',
                            style: TextStyleConstant().normal_1_22,
                          ),
                          TextSpan(
                            text: '"',
                            style: TextStyleConstant().shallow_gray_22,
                          ),
                        ]),
                      ),
                    )
                  ],
                ),
                Text(
                  "·如设立某个等级无升级规则将会按照顺序往不进行成长升级",
                  style: TextStyleConstant().shallow_gray_22,
                ),
                SizedBox(
                  height: 16.w,
                ),
                InkWell(
                  onTap: () {
                    showTextAlert(
                      context,
                      content: Container(
                        child: Text(
                          "如创建等级“白银会员”，会员充值或消费400元后打9折,\n 创建等级“黄金会员”，无升级规则，享受7折优惠,\n创建等级“钻石会员”会员充值或消费600元后打8折,\n顾客路人甲在店充值400元后将自动升级为“白银会员“，享受9折；\n顾客路人甲在店再次充值200元后将自动升级为“钻石会员”，享受8折；\n 因为“黄金会员”无升级规则所以跳过该等级按后续等级中有成长等级的会员等级升级。",
                          style: TextStyleConstant().normal_2_28,
                        ),
                      ),
                      onCancel: () {
                        Navigator.pop(context);
                      },
                      onConfirm: () {
                        Navigator.pop(context);
                      },
                      barrierDismissible: true,
                    );
                  },
                  child: Container(
                    child: Material(
                      color: Colors.white,
                      child: Text(
                        " 查看事例",
                        style: TextStyleConstant().origin_22,
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 6.w,
                ),
              ],
            ),
          )
        : Container();
  }

  imageTitle(dynamic item, int i) {
//    print(item["extra"]==null?'--':json.decode(item["extra"]));

    return InkWell(
      onTap: () {
        if (widget.needBack != true) {
          Future.delayed(Duration(milliseconds: 300), () async {
            var res = await Navigator.pushNamed(context, gradeAddandEdit.pageName, arguments: {'type': false, 'item': item});
            if (res != null) {
              queryStoreMemberRankFun();
            }
          });
        } else {
          Navigator.pop(context, item);
        }
      },
      child: Material(
        child: Container(
          color: Colors.white,
          child: Stack(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(
                  30.w,
                ),
                child: BaseImage(
                  '${"assets/image/memberAdministration1.png"}',
                  width: double.infinity,
                ),
              ),
              Positioned(
                top: 50.w,
                left: 0,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.only(
                        left: 82.w,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            "${item["rankName"] ?? '--'}",
                            style: TextStyleConstant().white_46,
                          ),
                          SizedBox(
                            height: 22.w,
                          ),
                          Text(
                            "${(item["discountCategory"] == 0 ? '无优惠' : (item["discountCategory"] == 1 ? '整单折扣' : '菜品会员价')) ?? '--'} ${item["discountCategory"] == 1 ? (item["extra"] == null ? '' : discountNumbrFormat((json.decode(item["extra"])["discountRate"] / 10).toString()).toString() + '折') : ''}",
                            style: TextStyleConstant().white_28,
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 54.w,
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        left: 82.w,
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                          width: 1,
                        ),
                        borderRadius: BorderRadius.circular(
                          24.w,
                        ),
                      ),
                      height: 48.w,
                      child: Center(
                        child: Text(
                          "   ${(item["upgradeConditionType"] == 1 ? '无升级条件' : (item["upgradeConditionType"] == 2 ? '充值' : (item["upgradeConditionType"] == 3 ? '消费' : '充值或消费'))) ?? '--'}   ${item["upgradeConditionType"] == 1 ? '' : ((item["targetAmount"]) == null ? '--' : (((item["targetAmount"] / 100)) == 0 ? '0元  ' : (((MoneyUtil.changeF2Y(item["targetAmount"] ?? 0))).toString() + '元  ')))}",
                          style: TextStyleConstant().white_26,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Positioned(
                right: 0,
                top: 60.w,
                bottom: 62.w,
                child: Padding(
                  padding: EdgeInsets.only(
                    right: 60.w,
                  ),
                  child: Container(
                    child: Icon(
                      _itemSort == false ? Icons.arrow_forward_ios : Icons.dehaze,
                      size: 30.w,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: widget.needBack != true ? '等级优惠' : '请选择',
        actions: <Widget>[
          if (!(widget.needBack ?? false))
            LabelButton(
              title: _itemSort == false ? '排序等级' : '保存',
              padding: EdgeInsets.only(left: 8, top: 2, bottom: 2),
              onTap: () {
                if (_itemSort == false) {
                  _itemSort = !_itemSort;
                  sortIdArr = [];
                  for (var z in cardList) {
                    sortIdArr.add(z["sort"]);
                  }
                } else {
                  sortModular(sortIdArr);
                  _itemSort = !_itemSort;
                }
                setState(() {});
              },
            )
        ],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  textHeader(),
                  _itemSort == false
                      ? Expanded(
                          child: SingleChildScrollView(
                            child: Column(
                              children: (cardList ?? [])
                                  .asMap()
                                  .keys
                                  .map((item) => Container(
                                        child: imageTitle(cardList[item], item),
                                      ))
                                  .toList(),
                            ),
                          ),
                        )
                      : Expanded(
                          child: ReorderableListView(
                              padding: EdgeInsets.only(bottom: 0.0),
                              children: (cardList ?? [])
                                  .asMap()
                                  .keys
                                  .map((item) => Container(
                                        key: Key(item.toString()),
                                        child: imageTitle(cardList[item], item),
                                      ))
                                  .toList(),
                              onReorder: (int oldIndex, int newIndex) {
                                sortIdArr = [];
                                var item = cardList.removeAt(oldIndex);
                                if (newIndex > cardList.length) {
                                  cardList.add(item);
                                } else {
                                  cardList.insert(newIndex, item);
                                }

                                for (var z in cardList) {
                                  sortIdArr.add(z["id"]);
                                }

                                setState(() {});
                              }),
                        ),
                ],
              ),
            ),
            widget.needBack != true
                ? FixedBottomBtn(
                    title: "新增等级",
                    onTap: () async {
                      var res = await Navigator.pushNamed(context, gradeAddandEdit.pageName, arguments: {
                        'type': true,
                      });
                      if (res != null) {
                        await queryStoreMemberRankFun();
                      }
                    },
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}
